package com.ruoyi.performance.service.impl;

import com.google.common.base.Joiner;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.performance.domain.PerfCheck;
import com.ruoyi.performance.domain.PerfLevelScore;
import com.ruoyi.performance.domain.PerfLevelTemplate;
import com.ruoyi.performance.dto.PerfLevelTemplateDto;
import com.ruoyi.performance.mapper.PerfLevelScoreMapper;
import com.ruoyi.performance.mapper.PerfLevelTemplateMapper;
import com.ruoyi.performance.service.PerfLevelTemplateService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ruoyi.performance.service.impl.PerfLevelScoreServiceImpl.INITIAL;
import static com.ruoyi.performance.utils.CompareArray.compareArray;

/**
 * @author YL
 * @date 2020-07-22
 * @description 绩效等级模板明细Service业务层处理
 */
@Service
@Slf4j
public class PerfLevelTemplateServiceImpl implements PerfLevelTemplateService {

    /**
     * 绩效模板发布状态
     */
    public static final String PUBLISH="1";
    /**
     * 等级上限分数
     */
    public static final int UPPER_SCORE=100;
    /**
     * 等级下限分数
     */
    public static final int LOWER_SCORE=0;

    @Resource
    private PerfLevelTemplateMapper perfLevelTemplateMapper;

    @Resource
    private PerfLevelScoreMapper perfLevelScoreMapper;

    /**
     * 根据id查找绩效等级模板
     *
     * @param id 绩效模板id
     * @return 绩效等级模板明细
     */
    @Override
    public PerfLevelTemplateDto selectPerfLevelTemplateById(int id) {
        return perfLevelTemplateMapper.selectPerfLevelTemplateById(id);
    }

    /**
     * 根据公司代码查找绩效等级模板
     *
     * @param companyCode 公司代码
     * @return 绩效等级模板明细
     */
    @Override
    public List<PerfLevelTemplateDto> selectPerfLevelTemplateByCompanyCode(String companyCode){
        return perfLevelTemplateMapper.selectPerfLevelTemplateByCompanyCode(companyCode);
    }

    /**
     * 查询绩效等级模板明细列表
     *
     * @param perfLevelTemplateDto 绩效等级模板明细
     * @return 绩效等级模板明细
     */
    @Override
    public List<PerfLevelTemplateDto> selectPerfLevelTemplateList(PerfLevelTemplateDto perfLevelTemplateDto) {
    	// 拆分状态字符串
    			List<String> statuslist = perfLevelTemplateDto.getStatuslist();
    			if (statuslist != null && statuslist.size() > 0) {
    				String status = "'" + StringUtils.join(statuslist, "','") + "'";
    				perfLevelTemplateDto.setStatus(status);
    			}
    	return perfLevelTemplateMapper.selectPerfLevelTemplateList(perfLevelTemplateDto);
    }

    /**
     * 新增绩效等级模板明细
     *
     * @param perfLevelTemplate 绩效等级模板明细
     * @return 结果
     */
    @Override
    public String insertPerfLevelTemplate(PerfLevelTemplate perfLevelTemplate) {
        //添加绩效模板时为初始状态
    	String result = "1";
        perfLevelTemplate.setStatus("0");
        if (perfLevelTemplateMapper.checkUnique(perfLevelTemplate))
        {
        	result =  perfLevelTemplate.getLevelTemplateCode() + "等级模板代码已存在，不允许重复添加!";
        	return result;
        }
        try {
			perfLevelTemplateMapper.insertPerfLevelTemplate(perfLevelTemplate);
		} catch (Exception e) {
			result = perfLevelTemplate.getLevelTemplateCode() + "模板新增失败，请联系管理员！";
			log.error(result, e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return result;
		}
        return result;
    }
    
    
    /**
     * 修改绩效等级模板明细
     *
     * @param perfLevelTemplate 绩效等级模板明细
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String updatePerfLevelTemplate(Map<String, List<PerfLevelTemplate>> datas)
    {   
    	String result = "1";
    	List<String> checkstatus = new ArrayList<String>();
    	for (PerfLevelTemplate perfLevelTemplate : datas.get("datas"))
    	{
    	int row= updateCheck(perfLevelTemplate);
    	String levelTemplateCode = perfLevelTemplate.getLevelTemplateCode();
		switch (row){
		    case -6:
			result = levelTemplateCode + "等级模板下无分数区间，禁止发布!";
			checkstatus.add(result);
			break;
			case -1:
				result = levelTemplateCode + "等级模板发布后禁止重复发布!";
				checkstatus.add(result);
				break;
			case -2:
				result = levelTemplateCode + "等级模板等级设计不符合要求!";
				checkstatus.add(result); 
				break;
			case -3:
				result = levelTemplateCode + "等级模板A等级上限分数应为100!";
				checkstatus.add(result); 
				break;
			case -4:
				result = levelTemplateCode + "等级模板最低等级的上限分数应大于0!";
				checkstatus.add(result);
				break;
			case -5:
				result = levelTemplateCode + "等级模板该等级模板分数分布错误!";
				checkstatus.add(result); 
				break;
			default:
			try {
				perfLevelTemplateMapper.updatePerfLevelTemplate(perfLevelTemplate);
			} catch (Exception e) {
				result = levelTemplateCode + "等级模更新失败,请联系管理员！";
				log.error(result, e);
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return result;
			}
			break;
		}
		if (checkstatus.size() > 0 && checkstatus != null) {
			result = Joiner.on(",").join(checkstatus);
		}
    	}
    	return result;
    }
    
    
    /**
     * 修改绩效等级模板明细(发布检查)
     *
     * @param perfLevelTemplate 绩效等级模板明细
     * @return 结果
     */
    public int updateCheck(PerfLevelTemplate perfLevelTemplate) {
        //等级模板ID
        int levelTemplateId=perfLevelTemplate.getId();
        //获取模板状态
        String status=perfLevelTemplateMapper.selectPerfLevelTemplateById(levelTemplateId).getStatus();
        //该模板的绩效等级
        List<String> levelCodes=perfLevelScoreMapper.selectPerfLevelCodeByLevelTemplateId(levelTemplateId);
        if (levelCodes.size() == 0 || levelCodes == null)
        {
        	return -6;
        }
        List<PerfLevelScore> levelScores=new ArrayList<>();
        PerfLevelScore perfLevelScore=new PerfLevelScore();
        perfLevelScore.setLevelTemplateId(levelTemplateId);
        //先判断模板是否已经发布
        if (!status.equals(INITIAL)){
            //模板发布后禁止修改
            return -1;
        }
        //发布绩效模板时，要校验其等级分数区间的正确性
        else if (perfLevelTemplate.getStatus().equals(PUBLISH)){
            //等级设计不符合要求时，返回-2
            List<String> rules=compareArray(levelCodes);
            if (rules== null){
                return -2;
            }else {
                //把分数区间按等级顺序重新排序
                for (String rule : rules) {
                    perfLevelScore.setLevelCode(rule);
                    PerfLevelScore levelScore=perfLevelScoreMapper.selectPerfLevelScoreByCode(perfLevelScore);
                    levelScores.add(levelScore);
                }
                //判断各等级分数是否符合要求
                if (levelScores.get(0).getUpperScore()!=UPPER_SCORE){
                    //A等级上限分数应为100
                    return -3;
                }
                if (levelScores.get(levelScores.size()-1).getUpperScore()<=LOWER_SCORE){
                    //最低等级的上限分数应大于0
                    return -4;
                }
                for (int i=0;i<levelScores.size()-1;i++){
                    //上一等级的下限分数是否与下一等级的上限分数衔接
                    int lowerScore=levelScores.get(i).getLowerScore();
                    int upperScore=levelScores.get(i+1).getUpperScore();
                    System.out.println(lowerScore+"==========="+upperScore);
                    if (lowerScore!=upperScore+1){
                        //该等级模板分数分布错误
                        return -5;
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 删除绩效等级模板明细
     *
     * @param id 模板id
     * @return 结果
     */
    @Override
    public String deletePerfLevelTemplateById(String ids) {
           
        String result = "1";
		List<String> checkstatus = new ArrayList<String>();
		String[] tmpids = ids.split(",");
		for (String tmpid : tmpids) {
			Long id = Long.valueOf(tmpid);
			PerfLevelTemplateDto perfLevelTemplate = perfLevelTemplateMapper.selectPerfLevelTemplateByIdL(id);
			String status = perfLevelTemplate.getStatus();
			if (status.equals(INITIAL)) {
				try {
					perfLevelScoreMapper.deletePerfLevelScoreByLevelTemplateId(id);
					perfLevelTemplateMapper.deletePerfLevelTemplateById(id);
				} catch (Exception e) {
					result = "删除分数模板失败,模板Id" + id + ",请联系管理员！";
					log.error(result, e);
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return result;
				}
			} else {
				result = "不允许删除已发布的模板！";
				checkstatus.add(result);
			}
		}
		if (checkstatus.size() > 0 && checkstatus != null) {
			result = Joiner.on(",").join(checkstatus);
		}
		return result;
    }
}
